package com.atguigu.lease.web.service.impl;

import com.atguigu.lease.config.MinioProperties;
import com.atguigu.lease.web.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        // 判断桶是否存在
        String bucketName = minioProperties.getBucketName();
        boolean exists = minioClient.bucketExists(bucketName);
        // 不存在，创建桶，设置访问权限
        if (!exists) {
            minioClient.makeBucket(bucketName);
            String policy = "{\n" +
                    "  \"Version\": \"2012-10-17\",\n" +
                    "  \"Statement\": [\n" +
                    "    {\n" +
                    "      \"Effect\": \"Allow\",\n" +
                    "      \"Principal\": \"*\",\n" +
                    "      \"Action\": \"s3:ListBucket\",\n" +
                    "      \"Resource\": \"arn:aws:s3:::" + bucketName + "\"\n" +
                    "    },\n" +
                    "    {\n" +
                    "      \"Effect\": \"Allow\",\n" +
                    "      \"Principal\": \"*\",\n" +
                    "      \"Action\": \"s3:GetObject\",\n" +
                    "      \"Resource\": \"arn:aws:s3:::"+ bucketName +"/*\"\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}";
            minioClient.setBucketPolicy(bucketName, policy);
        }
        // 向桶中上传文件
        PutObjectOptions putObjectOptions = new PutObjectOptions(file.getInputStream().available(), -1); // -1 表示不切割原有文件大小
        putObjectOptions.setContentType(file.getContentType());
        // 文件重名问题
        // 文件放在桶中不加区分的话显示太乱
        String objectName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" +
                UUID.randomUUID().toString().replace("-", "") + "_" + file.getOriginalFilename();
        minioClient.putObject(bucketName, objectName,
                file.getInputStream(),
                putObjectOptions);
        // 拼接返回的url地址
        return String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), objectName);
    }
}
